package bonecp.bonecp_src_read;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

public class TestListeningExecutorService {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TestListeningExecutorService test = new TestListeningExecutorService();
		// test.testExecutorService();
		test.listeningExecutorServiceTest();
		System.out.println("exit..");
	}

	private void listeningExecutorServiceTest()  {
		ListeningExecutorService executor = MoreExecutors
				.listeningDecorator(Executors.newFixedThreadPool(1));
		
		
		final ListenableFuture<String> future = executor
				.submit(new Callable<String>() {
					public String call() throws Exception {
						Thread.sleep(200);
						return "子线程结果";
					}
				});
		
/*		future.addListener(new Runnable() {
			public void run() {
				try {
					System.out.println(future.get());
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ExecutionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, Executors.newFixedThreadPool(1));*/
		
		Futures.addCallback(future, new FutureCallback<String>() {
			public void onSuccess(String result) {
				System.out.println(result);
			}

			public void onFailure(Throwable t) {
				System.out.println(t.getMessage());
			}
		});
	}

	
	
	private void testExecutorService() {
		ExecutorService executor = Executors.newFixedThreadPool(1);
		Future<String> future = executor.submit(new Callable<String>() {
			public String call() {
				return "Hello futue!";
			}
		});

		try {
			// Thread.sleep(1000);
			System.out.println(future.get());
		} catch (InterruptedException e) {
			future.cancel(true);
		} catch (ExecutionException e) {
			future.cancel(true);
		} finally {
			executor.shutdown();
		}
	}

}
